<template>
  <div @paste.native="copyHandler" style="position: relative">
    <div class="w-form-header">
      <div class="header">
        <div style="display: flex">
          <template v-if="isView != 1">
            <div v-if="type == 'create'">
              <el-button type="primary" @click="submitForm('保存')"
                >保存</el-button
              >
              <el-button type="success" @click="submitForm('提交')"
                >提交</el-button
              >
            </div>
            <div v-if="type == 'update' ">
              <div v-if="formData.status == '0'">
                <el-button type="primary" @click="submitForm('保存')"
                  >保存</el-button
                >
                <el-button type="success" @click="submitForm('提交')"
                  >提交</el-button
                >
              </div>
              <div v-else-if="formData.status == '2'">
                <el-button type="primary" @click=""
                  >修改</el-button
                >

                <el-button
                  type="primary"
                  style="margin-left: 10px"
                  @click="print"
                  :loading="printBtnLoading"
                  >打印</el-button
                >
              </div>
            </div>
          </template>
          <el-button v-else type="primary" @click="isView = 2">编辑</el-button>
        </div>

        <div class="title-box" >
            <span class="version"> 版本: {{ formData.version || "暂无" }}</span>
            <span class="status">{{ formData.statusStr }}</span>
          </div>
      </div>
    </div>
    <div class="admin-content ">
      <div class="gva-form-box">
        <div class="form-box">
          <div>
            <div class="">
              <div class="w-form-box">
                <div class="list-header">
                  基本资料

                  <el-button
                    type="primary"
                    @click="baseTongbu('手动')"
                    :disabled="isView == 1 || !formData.localStyleNum"
                    >同步</el-button
                  >
                </div>
                <div>
                  <el-descriptions title=" " border :column="4">
                    <template v-if="type!='create'">
                      <el-descriptions-item label="參考編號">
                      {{ formData.printingNum }}
                    </el-descriptions-item>
                    <el-descriptions-item label=""> </el-descriptions-item>
                    <el-descriptions-item label=""> </el-descriptions-item>
                    <el-descriptions-item label=""> </el-descriptions-item>
                    </template>
                   
                    <!-- <el-descriptions-item label="款式编号" v-if="type == 'update'">
                    <span>{{ formData.localStyleNum }}</span>
                  </el-descriptions-item> -->
                    <el-descriptions-item label="本厂款号" >
                      <template #label>
                        <div class="cell-item" title="必填">
                          <span style="color:red;">*</span>
                          <span>本厂款号</span>
                        </div>
                      </template>
                      <!-- <el-input
                        v-model="formData.localStyleNum"
                        placeholder="请输入"
                          :disabled="isView == 1"
                      /> -->
                      <el-select v-model="formData.localStyleNum" placeholder="请选择"
                        style="min-width: 120px; margin-right: 10px" filterable remote
                        :remote-method="remoteMethodlocalStyleNum" @change="localStyleNumChange">
                        <el-option v-for="item in localStyleNumList" :key="item.styleNum" :label="item.styleNum"
                          :value="item.styleNum" />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="印資類型">
                      <el-select
                        v-model="formData.printingTypeNum"
                        placeholder="请选择"
                        style="min-width: 150px"
                        :disabled="isView == 1"
                      >
                        <el-option
                          v-for="item in dict.printingTypeNum"
                          :key="item.value"
                          :label="item.value"
                          :value="item.value"
                        />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="生產單號">
                      <el-input
                        v-model="formData.productionOrderNum"
                        placeholder="请输入"
                        :disabled="isView == 1"
                      />
                    </el-descriptions-item>

                    <el-descriptions-item label="版本">{{
                      formData.version || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label="印資種類">
                      <template #label>
                        <div class="cell-item" title="必填">
                          <span style="color:red;">*</span>
                          <span>印資種類</span>
                        </div>
                      </template>
                      <el-select
                        v-model="formData.printingType"
                        placeholder="请选择"
                        style="min-width: 150px"
                        :disabled="isView == 1"
                      >
                        <el-option
                          v-for="item in mainMaterialList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="镜架类别">
                      {{ formData.glassFrameLens }}
                    </el-descriptions-item>

                    <el-descriptions-item label="PI交貨期">
                      {{ formData.piDeliveryDate || "" }}
                    </el-descriptions-item>

                    <el-descriptions-item label="審批人">
                      <!-- {{ styleNumSelectDetail.localStyleNum || "" }} -->
                    </el-descriptions-item>

                    <el-descriptions-item label="客户编号">{{
                      formData.customerNum
                    }}</el-descriptions-item>

                    <el-descriptions-item label="镜架材质">{{
                      formData.glassFrameMaterial
                    }}</el-descriptions-item>

                    <el-descriptions-item label="最早投產期">{{
                      formData.earliestProductionDate
                    }}</el-descriptions-item>

                    <el-descriptions-item label="创建人">
                        {{ formData.createdBy }}
                    </el-descriptions-item>

                    <el-descriptions-item label="客户款号">
                      <template #label>
                        <div class="cell-item" title="必填">
                          <span style="color:red;">*</span>
                          <span>客户款号</span>
                        </div>
                      </template>
                      <el-select
                        v-model="formData.customerStyleNum"
                        placeholder="请选择"
                        style="min-width: 150px"
                        :disabled="isView == 1"
                      >
                        <el-option
                          v-for="item in formData.customerStyleNumList"
                          :key="item"
                          :label="item"
                          :value="item"
                        />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="镜架结构"
                      >{{ formData.glassFrameStructure }}
                    </el-descriptions-item>

                    <el-descriptions-item label="排次週期">{{
                      formData.rowCycle
                    }}</el-descriptions-item>

                    <el-descriptions-item label="创建时间">
                      {{
                        formData.CreatedAt
                        
                      }}</el-descriptions-item
                    >
                    <!-- ? formatDate(
                              formData.CreatedAt,
                              "yyyy-MM-dd hh:mm:ss"
                            )
                          : "" -->
                    <el-descriptions-item label="品牌名稱">{{
                      formData.brandName || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label="尺碼">{{
                      formData.size || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label="部門">{{
                      formData.department || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label="更新人">
                     {{formData.updatedBy}}
                    </el-descriptions-item>

                    <el-descriptions-item label="走地">
                      <template #label>
                        <div class="cell-item" title="必填">
                          <span style="color:red;">*</span>
                          <span>走地</span>
                        </div>
                      </template>
                      {{
                      formData.ground || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label="客戶尺碼">{{
                      formData.customerSize || ""
                    }}</el-descriptions-item>

                    <el-descriptions-item label=""></el-descriptions-item>

                    <el-descriptions-item label="更新时间">
                      {{
                        formData.UpdatedAt
                      }}
                    </el-descriptions-item>

                    <el-descriptions-item label="系列">{{
                      formData.series
                    }}</el-descriptions-item>

                    <el-descriptions-item label="印資部位">
                      <el-select
                        v-model="formData.printingPart"
                        :placeholder="`请选择`"
                        style="width: 100%"
                        :clearable="true"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :disabled="isView == 1"
                        @change="printingPartChange"
                      >
                        <el-option
                          v-for="(item, index) in printingPartList"
                          :key="index"
                          :label="item.label"
                          :value="item.label"
                        />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="包裝部位">
                      <el-select
                        v-model="formData.packagingPart"
                        :placeholder="`请选择`"
                        style="min-width: 150px"
                        :clearable="true"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :disabled="isView == 1"
                        @change="packagingPartChange"
                      >
                        <el-option
                          v-for="(item, index) in packagingPartList"
                          :key="index"
                          :label="item.label"
                          :value="item.label"
                        />
                      </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="圖紙編號">
                      <div style="display: flex;">
                        <a v-if="formData.printingImages" :href="path+formData.printingImages.filePath" target="_blank" style="margin-right: 6px;" >{{ formData.printingImages.fileName }}</a>
                      <el-upload
                        :action="`${path}/fileUploadAndDownload/upload`"
                        :on-error="uploadError3"
                        :on-success="uploadSuccess3"
                        :headers="{
                          'x-token': xToken,
                          'x-user-id': xUserId,
                          Authorization: `Bearer ${xToken}`,
                        }"
                        :show-file-list="false"
                        class="upload-btn"
                      >
                        <span style="text-decoration: underline;color: blue">上传图纸</span>
                      </el-upload>
                      </div>
                     
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-tabs type="border-card" class="tabs-box" v-model="tabsValue2">
        <el-tab-pane name="tabsValue1a">
          <template #label>
            <div
              :class="[
                {
                  'custom-tabs-label-isEdit': !isEditProductTab,
                },
                'custom-tabs-label',
              ]"
            >
              印资部分
            </div>
          </template>
          <div
            class="gva-form-box"
            v-for="(item, index) in formData.printingPartItem"
            :key="index"
          >
            <div class="w-form-box">
              <div class="list-header">
                {{ item.label }}
                <el-button
                  type="primary"
                  @click="printingPartItemAddLine(item.table)"
                  :disabled="isView == 1"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  @click="deleteLine(item)"
                  :disabled="isView == 1 || item.multipleSelection?.length == 0"
                  >删除</el-button
                >
                <el-button type="primary" @click="" :disabled="isView == 1"
                  >导出</el-button
                >
                <el-button type="primary" @click="" :disabled="isView == 1"
                  >批量导出</el-button
                >
              </div>
              <div>
                <el-row>
                  <el-col :span="16">
                    <el-table
                      :data="item.table"
                      style="width: 100%"
                      border
                      @selection-change="handleSelectionChange($event, item)"
                    >
                      <el-table-column type="selection" width="50" />
                      <el-table-column prop="sizeNum" label="位置">
                        <template #default="{ row }">
                          <el-select
                            v-model="row.position"
                            :placeholder="`请选择`"
                            style="width: 100%"
                            :disabled="isView == 1"
                          >
                            <el-option
                              v-for="(item, index) in item.selectList"
                              :key="index"
                              :label="item.location"
                              :value="item.location"
                            />
                          </el-select>
                        </template>
                      </el-table-column>

                      <el-table-column label="做法">
                        <template #default="{ row }">
                          <el-input v-model="row.method" placeholder="请输入" :disabled="isView == 1"/>
                        </template>
                      </el-table-column>

                      <el-table-column label="編號">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.ref"
                            placeholder="请输入"
                            :disabled="isView == 1"
                          />
                        </template>
                      </el-table-column>

                      <el-table-column label="客色號">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.customerColorNumber"
                            placeholder="请输入"
                            :disabled="isView == 1"
                          />
                        </template>
                      </el-table-column>

                      <el-table-column label="油色">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.oilColor"
                            placeholder="请输入"
                            :disabled="isView == 1"
                          />
                        </template>
                      </el-table-column>

                      <el-table-column label="说明">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.explain"
                            placeholder="请输入"
                            :disabled="isView == 1"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                  <el-col :span="8" style="position: relative">
                    <div
                      class="right-img-box"
                      :class="{
                        selectItem: selectImgBox == `tabsValue1a,${index}`,
                      }"
                      @click="selectImgBoxChange(`tabsValue1a,${index}`)"
                    >
                      <el-icon
                        size="120"
                        color="#999"
                        v-if="!item.image.filePath"
                        ><PictureFilled
                      /></el-icon>
                      <img
                        v-else
                        :src="path + item.image.filePath"
                        class="cusImg"
                        alt=""
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane name="tabsValue1b">
          <template #label>
            <div
              :class="[
                {
                  'custom-tabs-label-isEdit': !isEditDesignTab,
                },
                'custom-tabs-label',
              ]"
            >
              包装部分
            </div>
          </template>
          <div
            class="gva-form-box"
            v-for="(item, index) in formData.packagingPartItem"
            :key="index"
          >
            <div class="w-form-box">
              <div class="list-header">
                {{ item.label }}
                <el-button
                  type="primary"
                  @click="packagingPartItemAddLine(item.table)"
                  :disabled="isView == 1"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  @click="deleteLine(item)"
                  :disabled="isView == 1 || item.multipleSelection?.length == 0"
                  >删除</el-button
                >
                <el-button type="primary" @click="" :disabled="isView == 1"
                  >导出</el-button
                >
                <el-button type="primary" @click="" :disabled="isView == 1"
                  >批量导出</el-button
                >
              </div>
              <div>
                <el-row>
                  <el-col :span="16">
                    <el-table
                      :data="item.table"
                      style="width: 100%"
                      border
                      @selection-change="handleSelectionChange($event, item)"
                    >
                      <el-table-column type="selection" width="50" />
                      <el-table-column prop="sizeNum" label="包装物料">
                        <template #default="{ row }">
                          <el-select
                            v-model="row.packagingMaterial"
                            :placeholder="`请选择`"
                            style="width: 100%"
                            :disabled="isView == 1"
                          >
                            <el-option
                              v-for="(item, index) in item.selectList"
                              :key="index"
                              :label="item.location"
                              :value="item.location"
                            />
                          </el-select>
                        </template>
                      </el-table-column>

                      <el-table-column label="数量">
                        <template #default="{ row }">
                          <el-input-number  v-model="row.number" style="width: 100%" :max="1000" :min="0"
                          :controls="false"  placeholder="请输入" 
                          :disabled="isView == 1" />
                        </template>
                      </el-table-column>

                      <el-table-column label="編號">
                        <template #default="{ row }">
                          <el-input
                          :disabled="isView == 1"
                            v-model="row.ref"
                            placeholder="请输入"
                          />
                        </template>
                      </el-table-column>

                      <el-table-column label="客色號">
                        <template #default="{ row }">
                          <el-input
                          :disabled="isView == 1"
                            v-model="row.customerColorNumber"
                            placeholder="请输入"
                          />
                        </template>
                      </el-table-column>

                      <el-table-column label="銷售組織" v-if="formData.brandName == 'LEVIS' ||
                        formData.brandName == 'levis' ||
                        formData.brandName == 'fila' ||
                        formData.brandName == 'FILA'">
                        <template #default="{ row }">
                          <el-checkbox-group v-model="row.salesOrganization" :disabled="isView == 1">
                            <el-checkbox label="1000" value="1000" />
                            <el-checkbox label="9000" value="9000" />
                          </el-checkbox-group>
                        </template>
                      </el-table-column>

                      <el-table-column label="说明">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.explain"
                            placeholder="请输入"
                            :disabled="isView == 1"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                  <el-col :span="8" style="position: relative">
                    <div
                      class="right-img-box"
                      :class="{
                        selectItem: selectImgBox == `tabsValue1b,${index}`,
                      }"
                      @click="selectImgBoxChange(`tabsValue1b,${index}`)"
                    >
                      <el-icon
                        size="120"
                        color="#999"
                        v-if="!item.image.filePath"
                        ><PictureFilled
                      /></el-icon>
                      <img
                        v-else
                        :src="path + item.image.filePath"
                        class="cusImg"
                        alt=""
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="gva-form-box">
        <div class="w-form-box">
          <div class="list-header">备注</div>
          <div>
            <el-input
              v-model="formData.content"
              style="width: 100%"
              autosize
              type="textarea"
              :maxlength="1000"
              placeholder="请输入"
              :disabled="isView == 1"
            />
          </div>
        </div>
      </div>

      <div class="gva-form-box">
        <div class="w-form-box">
          <div class="list-header">
            邮件附件

            <el-button
              type="primary"
              @click="openUploadDialog"
              :disabled="isView == 1"
              >上传</el-button
            >
          </div>
          <div>
            <el-table :data="formData.printingCapitalAttachments" border style="width: 100%">
              <el-table-column label="描述" prop="desc" width="400">
                <template #default="scope">
                  <el-input
                    :maxlength="100"
                    v-model="scope.row.desc"
                    :clearable="true"
                    placeholder="请输入"
                    :disabled="isView == 1"
                  />
                </template>
              </el-table-column>
              <el-table-column label="附件文件" prop="fileUrl" width="300">
                <template #default="scope">
                  <a href="javascript:" @click.stop="downloadFile(scope.row)">{{
                    scope.row.fileName
                  }}</a>
                </template>
              </el-table-column>
              <el-table-column label="上传时间" prop="UpdatedAt">
                <template #default="scope">
                  <span>
                    {{
                      formatDate(scope.row.UpdatedAt, "yyyy-MM-dd hh:mm:ss")
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="上传人" prop="uploadUser">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <!-- BOM附件长传弹窗 -->
    <el-dialog v-model="uploadDialogVisible" title="文件上传" width="800">
      <el-input
        v-model="desc"
        style="width: 100%; margin-bottom: 10px"
        :rows="3"
        :maxlength="100"
        type="textarea"
        placeholder="请输入文件描述"
      />
      <el-upload
        :action="`${path}/fileUploadAndDownload/upload`"
        :on-error="uploadError"
        drag
        :on-success="uploadSuccess"
        :headers="{
          'x-token': xToken,
          'x-user-id': xUserId,
          Authorization: `Bearer ${xToken}`,
        }"
        :show-file-list="false"
        class="upload-btn"
      >
        <el-button type="primary">上传</el-button>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onBeforeUnmount, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useDict } from "@/utils/dictionary";
import {
  printingCapitalSync,
  fileUploadAndDownload,
  linkage,
  printingCapitalCreate,
  findPrintingCapital,
  getLocalStyleNumList,
} from "@/api/printedMaterial.js";
import { formatDate } from "@/utils/format";
import { useRoute, useRouter } from "vue-router";
import { emitter } from "@/utils/bus.js";
export default {
  name: "printedMaterialDetail",
  setup() {
    const route = useRoute();
    const state = reactive({
      type:'create',
      isView: 1,
      tabsValue2: "tabsValue1a",
      desc:'',
      printBtnLoading:false,
      formData: {},
      selectImgBox: 0,
      uploadDialogVisible: false,
      dict: {},
      localStyleNumList:[],
      multipleSelection: [],
      printingPartList: [
        {
          label: "膠袋/卡紙",
          image: {
            // id: 2,
            // fileName: "acv",
            // filePath: "uploads/file/printing/image/acv.jpg",
            // fileType: 2,
            // fileSize: 0
          },
          table: [],
          multipleSelection: [],
        },
        {
          label: "测试2",
          image: {
            // id: 2,
            // fileName: "acv",
            // filePath: "uploads/file/printing/image/acv.jpg",
            // fileType: 2,
            // fileSize: 0
          },
          multipleSelection: [],
          table: [],
        },
      ], //印資部位选项
      packagingPartList: [
        {
          label: "包装测试1",
          image: {
            // id: 2,
            // fileName: "acv",
            // filePath: "uploads/file/printing/image/acv.jpg",
            // fileType: 2,
            // fileSize: 0
          },
          table: [],
          multipleSelection: [],
        },
        {
          label: "包装测试2",
          image: {
            // id: 2,
            // fileName: "acv",
            // filePath: "uploads/file/printing/image/acv.jpg",
            // fileType: 2,
            // fileSize: 0
          },
          multipleSelection: [],
          table: [],
        },
      ], //包裝部位选项
    });
    const path = ref(import.meta.env.VITE_BASE_API);

    async function init(params) {

      linkage({ position: 1 }).then((res) => {
        if (res.code == 0) {
          state.printingPartList = [];
          for (const key in res.data) {
            state.printingPartList.push({
              label: key,
              image: {},
              multipleSelection: [],
              table: [],
              selectList: res.data[key],
            });
          }
        }
      });
      linkage({ position: 2 }).then((res) => {
        if (res.code == 0) {
          state.packagingPartList = [];
          for (const key in res.data) {
            state.packagingPartList.push({
              label: key,
              image: {},
              multipleSelection: [],
              table: [],
              selectList: res.data[key],
            });
          }

        }
      });

      state.dict = await useDict("printingTypeNum");

      if (route.query.printingNum)  {
        state.type = "update";
        findPrintingCapital({printingNum:route.query.printingNum}).then(res=>{
         console.log(res);
         if(res.code==0) {
          state.formData = {...res.data}
          state.formData.packagingPart =  state.formData.packagingPart.split(',')
          state.formData.printingPart =  state.formData.printingPart.split(',')
          state.formData.printingPartItem?.forEach(item=>{
            item.selectList = state.printingPartList.filter(it=>it.label==item.label)[0].selectList
          })
          state.formData.packagingPartItem?.forEach(item=>{
            item.selectList = state.packagingPartList.filter(it=>it.label==item.label)[0].selectList
          })
         }
        })
      }else {
        state.isView=2
      }
      formData.isProduct = route.query.isProduct
    }
    function selectImgBoxChange(params) {
      state.selectImgBox = params;
      console.log(state.selectImgBox);
    }

    const handleSelectionChange = (val, item) => {
      item.multipleSelection = val;
    };

    // 获取本厂款号列表
    const remoteMethodlocalStyleNum = (keyword) => {
      getLocalStyleNumList({
        page: 1,
        pageSize: 50,
        styleNum: keyword ? keyword : undefined,
        status: 1,
        searchType: "masterBom",
        productSpecStatus: 1,
      }).then((res) => {
        if (res.code == 0) {
          state.productStylesList = res.data.list;
        }
      });
    };

    function customizeUpload(file) {
      const formData = new FormData();
      formData.append("file", file);
      fileUploadAndDownload(formData).then((res) => {
        console.log(res.data);

        if (res.code == 0) {
          if (state.selectImgBox.includes("tabsValue1a")) {
            state.formData.printingPartItem[
              state.selectImgBox.split(",")[1]
            ].image = {
              ID: res.data.file.ID,
              fileName: res.data.file.name,
              filePath: res.data.file.url,
            };
          } else if (state.selectImgBox.includes("tabsValue1b")) {
            state.formData.packagingPartItem[
              state.selectImgBox.split(",")[1]
            ].image = {
              ID: res.data.file.ID,
              fileName: res.data.file.name,
              filePath: res.data.file.url,
            };
          }
        }
      });
    }

    //粘贴事件
    function copyHandler(e) {
      if (!state.selectImgBox) {
        return;
      }
      // 处理用户频繁粘贴操作
      let now = new Date().getTime();
      if (now - this.timeStep < 500) {
        ElMessage({
          type: "warning",
          message: "粘贴速度太频繁！请稍后再试",
        });
        return;
      }
      this.timeStep = now;
      var clipboardData = e.clipboardData; // IE
      if (!clipboardData) {
        //chrome
        clipboardData = e.originalEvent.clipboardData;
      }
      var items = "";
      items = (e.clipboardData || window.clipboardData).items;
      let file = null;
      if (!items || items.length === 0) {
        ElMessage.error({
          type: "warning",
          message: "当前浏览器不支持粘贴本地图片，请打开图片复制后再粘贴！",
        });
        return;
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        file = items[i].getAsFile();
      }
      console.log(state.selectImgBox);
      console.log(file);
      // 对复制黏贴的类型进行判断，若是非文件类型，比如复制黏贴的文字，则不会调用上传文件的函数
      if (file) {
        // 生成预览图
        // this.$refs.uploadRef.handleStart(file);
        //上传图片方法
        customizeUpload(file);
      }
    }

    // 限制只能上传图片
    function beforeUpload(file) {
      const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
      const isAllowed = allowedTypes.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isAllowed) {
        ElMessage.error("只能上传JPG/PNG/GIF格式的图片!");
      }
      if (!isLt2M) {
        ElMessage.error("上传图片大小不能超过 2MB!");
      }
      return isAllowed && isLt2M;
    }

    const uploadSuccess = (res) => {
      if (res.code == 0) {
        const { data } = res;
        if (data.file) {
          let datas = {
            desc: state.desc,
            fileUrl: data.file.url,
            uploadTime: data.file.CreatedAt,
            uploadUser: data.file.uploadUser,
            fileName: data.file.name,
          };
          if(state.formData.printingCapitalAttachments) {
            state.formData.printingCapitalAttachments.push(datas)
          }else {
            state.formData.printingCapitalAttachments=[datas]
          }
          ElMessage({
            type: "success",
            message: "上传成功",
          });
          state.uploadDialogVisible = false;
          state.desc = "";
        }
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
    };

    const uploadError = () => {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
      state.fullscreenLoading = false;
    };

    const uploadSuccess3 = (res) => {
      if (res.code == 0) {
        const { data } = res;
        if (data.file) {
          state.formData.printingImages = {
            desc: state.desc,
            filePath: data.file.url,
            uploadTime: data.file.CreatedAt,
            uploadUser: data.file.uploadUser,
            fileName: data.file.name,
          };
          
          ElMessage({
            type: "success",
            message: "上传成功",
          });
        }
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
    };

    const uploadError3 = () => {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
    };

    function openUploadDialog(params) {
      state.uploadDialogVisible = true;
    }

    // 同步基础信息
    function baseTongbu(params) {
      if (!state.formData.localStyleNum) {
        ElMessage({
          type: "warning",
          message: "请输入本厂款号",
        });
        return;
      }
      printingCapitalSync({ localStyleNum: state.formData.localStyleNum,productionOrderNum:'PS10023' }).then(
        (res) => {
          if (res.code == 0) {
            for (const key in res.data) {
              state.formData[key] = res.data[key];
            }
            state.formData = {...state.formData,...res.data.sapResp}
          }
        }
      );
    }

    function printingPartChange(params) {
      state.formData.printingPartItem = state.printingPartList.filter((item) => {
        return params.includes(item.label);
      });
    }

    function packagingPartChange(params) {
      state.formData.packagingPartItem = state.packagingPartList.filter((item) => {
        return params.includes(item.label);
      });
    }

    function printingPartItemAddLine(params) {
      params.push({
        sid: Math.random(),
        position:'',//位置
        oilColor: "",//油色
        method: "",//做法
        customerColorNumber: "",//可色号
        explain: "",//说明
        ref: "",//编号
      });
    }

    function packagingPartItemAddLine(params) {
      params.push({
        sid: Math.random(),
        salesOrganization: "", // 销售组织
        packagingMaterial: "", // 包装物料
        number: 1, // 数量
        customerColorNumber: "", // 客色号
        explain: "", // 说明
        ref: "", //编号
      });
    }

    function deleteLine(item) {
      item.table = item.table.filter(
        (it) => !item.multipleSelection.map((val) => val.sid).includes(it.sid)
      );
    }

    function submitForm(params) {
      if(!state.formData.localStyleNum) {
        ElMessage({
          type: "warning",
          message: "请输入本厂款号",
        });
        return;
      }
      let datas = {...state.formData}
      if(datas.packagingPart&&datas.packagingPart.length) {
        datas.packagingPart = datas.packagingPart.join(',')
      }
      if(datas.printingPart&&datas.printingPart.length) {
        datas.printingPart = datas.printingPart.join(',')
      }
      datas.printingType='1'
      datas.ground='走地走地'
      console.log(state.formData);
      printingCapitalCreate(datas).then(res=>{
        if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "保存成功",
            });
            emitter.emit("closeThisPage");
            // 获取当前URL
            const currentUrl = new URL(window.location.href);
            window.location.href =
              currentUrl.href +
              "?printingNum=" +
              res.data.printingNum +
              "&subTitle=" +res.data.printingNum;
          }
      })
    }

    onMounted(async () => {
      init();
    });

    return {
      ...toRefs(state),
      selectImgBoxChange,
      copyHandler,
      path,
      beforeUpload,
      uploadSuccess,
      baseTongbu,
      printingPartChange,
      printingPartItemAddLine,
      handleSelectionChange,
      deleteLine,
      packagingPartChange,
      packagingPartItemAddLine,
      openUploadDialog,
      uploadError,
      submitForm,
      formatDate,
      uploadSuccess3,
      uploadError3,
      remoteMethodlocalStyleNum,
    };
  },
};
</script>
<style lang="scss" scoped>
.form-header {
  font-size: 22px;
  font-weight: 600;
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #ccc5;
}

.form-box {
  margin: 0 auto;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.jianlishipipeijianzhudang {
  :deep(.el-select__suffix) {
    display: none;
  }

  :deep(.cell) {
    display: flex;
    align-items: center;
  }

  :deep(.el-select__wrapper) {
    padding: 4px;
  }
}

.custom-table-header {
  display: flex;
  align-items: center;
  background-color: #f7fbff;
  border: 1px solid rgb(232 234 236);
  color: rgb(55 65 81);
  font-weight: bold;

  > div {
    padding: 14px 0px;
    padding-left: 10px;
    border-right: 1px solid rgb(232 234 236);
    flex: 10;
  }
}

:deep(.el-descriptions__label) {
  min-width: 80px !important;
}

:deep(.el-descriptions__cell) {
  min-width: 140px;

  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper {
    width: unset;
    min-width: 100px;
  }
}
</style>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-box {
  display: flex;
  align-items: center;

  .title {
    font-size: 20px;
    font-weight: 600;
    margin-right: 8px;
  }
}

:deep(.el-tabs--border-card > .el-tabs__content) {
  padding: 0;
}
:deep(.el-tabs--border-card) {
  border: none;
}
:deep(.el-tabs__nav) {
  border-left: 1px solid #e4e7ed;
}

.custom-tabs-label {
  padding: 0 20px;
  color: #999;
  line-height: 40px;
}
.custom-tabs-label-isEdit {
  color: #999;
}
.collapse-items {
  :deep(.el-collapse-item__header) {
    position: relative;
  }
  .collapse-left {
    position: absolute;
    top: -6px;
    right: 46px;
    font-weight: 500;
  }
}
.tabs-box {
  :deep(.el-tabs__header .el-tabs__item) {
    padding: 0 !important;
  }
}

.right-img-box {
  margin-left: 10px;
  height: 200px;
  border: 2px dashed #999;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cusImg {
  width: 100%; /* 使图片宽度自适应容器 */
  height: 100%; /* 使图片高度自适应容器 */
  object-fit: contain; /* 裁剪并覆盖到容器 */
  border-radius: 12px;
}

.selectItem {
  border: 2px solid;
  border-color: var(--el-color-primary);
}
</style>
<style scoped>
.avatar-uploader {
  margin-left: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
